package jmine.tec.di.type;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import bancosys.tec.utils.date.Date;

/**
 * {@link TypeConverter} para {@link Date} Usa o dateFormat passado no construtor
 * 
 * @author takeshi
 */
public class DateTypeConverter implements TypeConverter<Date> {

    private final String dateFormat;

    private final boolean lenient;

    /**
     * @param dateFormat o date format, como esperado por {@link SimpleDateFormat}
     * @param lenient se true, p parse sera leniente
     */
    public DateTypeConverter(String dateFormat, boolean lenient) {
        super();
        this.dateFormat = dateFormat;
        this.lenient = lenient;
    }

    /**
     * {@inheritDoc}
     */
    public Date convert(String value, Class<?> desiredType) throws TypeConvertionException {
        DateFormat df = new SimpleDateFormat(this.dateFormat);
        df.setLenient(this.lenient);
        try {
            return new Date(df.parse(value));
        } catch (ParseException e) {
            throw new TypeConvertionException(e, Date.class, value);
        }
    }

    /**
     * {@inheritDoc}
     */
    public boolean isTypeCompatible(Class<?> declaredRawType) {
        return Date.class == declaredRawType;
    }

}
